/**
 * 薪资意向
 */
import React, { useState } from 'react';
import useDictionary from '@/hooks/useDictionary';
import { InputItem, Toast, TextareaItem, Modal, Picker } from 'antd-mobile';
import { Spin } from 'antd';
import { router, withRouter } from 'umi';
import { createForm } from 'rc-form';
import FileUploadMobile from '@/components/Mobile/FileUploadMobile';
import add from '@/components/Mobile/FileUploadMobile/icon-add.png';
import { useFormChange, useInterviewCandidate } from '@/pages/RecruitEmail/hooks';
import { hasIn, size } from 'lodash';
import { updateSalaryWill } from '../service';
import { EditListItem, Button, PageWrap } from './components';
import xIcon from '../images/icon-x.png';
import style from './BackgroundIntensions.less';

const BackgroundIntensions = ({ location, form }) => {
    const { query } = location;
    const { getFieldProps } = form;
    const [submitLoading, setSubmitLoading] = React.useState(false);
    const [current, setCurrent] = React.useState();
    const { data: talentInfo, loading } = useInterviewCandidate(query.nid);
    const [currencyTypeList] = useDictionary('currencyType');
    const [pickerArr, setPickerArr] = useState([]);
    React.useEffect(() => {
        if (currencyTypeList) {
            const tempArr = [];
            currencyTypeList.forEach(item => {
                tempArr.push({
                    ...item,
                    label: `${item.value}(${item.dictName})`
                });
            });
            setPickerArr(tempArr);
        }
    }, [currencyTypeList]);

    const handleSubmit = () => {
        form.validateFields(async (err, values) => {
            if (!err) {
                const params = {
                    employId: talentInfo.employId,
                    currentMonthSalary: values.currentMonthSalary ? Number(values.currentMonthSalary) : '',
                    expectMonthNumber: Number(values.expectMonthNumber),
                    expectSalary: Number(values.expectSalary),
                    monthCount: Number(values.monthCount),
                    currentSalaryDesc: values?.currentSalaryDesc || '',
                    salaryProveRelations: values?.salaryProveRelationsList?.uploadResourceFile
                        ? [values?.salaryProveRelationsList?.uploadResourceFile]
                        : [],
                    currentSalaryCurrencyCode: values.currentSalaryCurrencyCode
                        ? values.currentSalaryCurrencyCode[0]
                        : ''
                };
                setSubmitLoading(true);
                updateSalaryWill(params)
                    .then(res => {
                        const { code, msg } = res;
                        if (code === 10000) {
                            // Toast.info('提交成功');
                            history.goBack();
                        } else {
                            Toast.info(msg);
                        }
                    })
                    .finally(() => {
                        setSubmitLoading(false);
                    });
            } else {
                const tempList = Object.values(err);
                if (tempList && tempList.length > 0) {
                    const { errors } = tempList[0];
                    Toast.info(errors[0]?.message);
                }
            }
        });
    };
    const { hasFormChange, initialForm } = useFormChange(form);
    const handleLeftClick = () => {
        if (hasFormChange()) {
            Modal.alert('存在未保存的内容，确定退出吗？', '', [
                { text: '取消' },
                {
                    text: '确定',
                    onPress: () => {
                        history.goBack();
                    }
                }
            ]);
        } else {
            history.goBack();
        }
    };
    React.useEffect(() => {
        if (!loading) {
            initialForm();
        }
    }, [loading]);
    React.useEffect(() => {
        const values = form.getFieldsValue();
        if (current) {
            // 原月薪年薪计算
            const currentMonthSalary = (values.yearSalary / values.monthCount).toFixed(0);
            const yearSalary = (values.currentMonthSalary * values.monthCount).toFixed(0);
            if (current.yearSalary !== values.yearSalary) {
                const finalParams = {
                    ...values,
                    currentMonthSalary: currentMonthSalary > 0 ? currentMonthSalary : undefined
                };
                setCurrent(finalParams);
                form.setFieldsValue(finalParams);
            } else if (
                current.currentMonthSalary !== values.currentMonthSalary ||
                current.monthCount !== values.monthCount
            ) {
                const finalParams = {
                    ...values,
                    yearSalary: yearSalary > 0 ? yearSalary : undefined
                };
                setCurrent(finalParams);
                form.setFieldsValue(finalParams);
            }
            // 期望月薪年薪
            if (current.expectSalary !== values.expectSalary) {
                const finalParams = {
                    ...values,
                    expectMonthSalary: (values.expectSalary / values.expectMonthNumber).toFixed(0)
                };
                setCurrent(finalParams);
                form.setFieldsValue(finalParams);
            } else if (
                current.expectMonthSalary !== values.expectMonthSalary ||
                current.expectMonthNumber !== values.expectMonthNumber
            ) {
                const finalParams = {
                    ...values,
                    expectSalary: (values.expectMonthSalary * values.expectMonthNumber).toFixed(0)
                };
                setCurrent(finalParams);
                form.setFieldsValue(finalParams);
            }
        } else {
            setCurrent(values);
        }
        // console.log(values);
        // console.log('触发');
    }, [form.getFieldsValue()]);

    const getMonthSalary = (s, m) => {
        if (s && m) {
            return (s / m).toFixed(0);
        }
        return '';
    };
    const getCurrentYearSalary = (currentMonthSalary, monthCount) => {
        // 仅为显示placeholder
        const currentYearSalary = currentMonthSalary * monthCount;

        if (Number.isNaN(currentYearSalary)) return undefined;
        return parseInt(currentYearSalary, 10) || undefined;
    };

    const getinitialVal = () => {
        if (talentInfo?.recruitTalentBackgroundSalary?.currentSalaryCurrencyCode) {
            return [talentInfo?.recruitTalentBackgroundSalary?.currentSalaryCurrencyCode];
        }
        if (talentInfo?.recruitTalentBackgroundSalary?.companyCurrencyCode) {
            return [talentInfo?.recruitTalentBackgroundSalary?.companyCurrencyCode];
        }
        return ['CNY'];
    };
    const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
    let moneyKeyboardWrapProps;
    if (isIPhone) {
        moneyKeyboardWrapProps = {
            onTouchStart: e => e.preventDefault()
        };
    }

    const formatSalaryInput = (val, int, decimal, type) => {
        let newVal = val
            .toString()
            .replace(/[^\d.]/g, '')
            .replace(/\.{2,}/g, '.')
            .replace(/^\./g, '')
            .replace('.', '$#$')
            .replace(/\./g, '')
            .replace('$#$', '.');
        const formatNewVal = newVal.split('.');
        if (formatNewVal.length === 2) {
            let intVal = newVal.split('.')[0];
            let decimalVal = newVal.split('.')[1];
            if (intVal.length > int) {
                intVal = intVal.substring(0, int);
            }
            if (decimalVal.length > decimal) {
                decimalVal = decimalVal?.substring(0, decimal);
            }
            newVal = `${intVal}.${decimalVal}`;
        } else {
            newVal = newVal.substring(0, int);
        }
        if (type === 'oldYear') {
            form.setFieldsValue({ ...form.getFieldsValue(), yearSalary: newVal });
        } else if (type === 'oldMonth') {
            form.setFieldsValue({ ...form.getFieldsValue(), currentMonthSalary: newVal });
        } else if (type === 'expectYear') {
            form.setFieldsValue({ ...form.getFieldsValue(), expectSalary: newVal });
        } else if (type === 'expectMonth') {
            form.setFieldsValue({ ...form.getFieldsValue(), expectMonthSalary: newVal });
        }
    };
    const monthInputVal = val => {
        formatSalaryInput(val, 8, 4, 'oldMonth');
    };
    const yearInputVal = val => {
        formatSalaryInput(val, 12, 8, 'oldYear');
    };
    const expectMonthInputVal = val => {
        formatSalaryInput(val, 8, 4, 'expectMonth');
    };
    const expectYearInputVal = val => {
        formatSalaryInput(val, 12, 8, 'expectYear');
    };
    return (
        <PageWrap
            title="薪资意向"
            navbarProps={{ onLeftClick: handleLeftClick }}
            footer={
                <Button type="primary" loading={submitLoading} onClick={handleSubmit}>
                    保存
                </Button>
            }
        >
            <div style={{ padding: '0 16px 150px' }}>
                <Spin spinning={loading}>
                    {query.workStatus !== 3 && (
                        <>
                            <EditListItem showArrow>
                                <div className={style.currencyWrapper}>
                                    <span className={style.title}>原结算货币</span>
                                    <Picker
                                        className={style.customPicker}
                                        extra="请选择"
                                        cols={1}
                                        data={pickerArr}
                                        title="结算货币"
                                        {...getFieldProps('currentSalaryCurrencyCode', {
                                            initialValue: getinitialVal(),
                                            rules: [{ required: true, message: '请选择原结算货币' }]
                                        })}
                                    >
                                        <span className={style.currencyBtn}>
                                            {form.getFieldValue('currentSalaryCurrencyCode')}
                                        </span>
                                    </Picker>
                                </div>
                            </EditListItem>
                            <EditListItem title="原月薪" showArrow={false}>
                                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                                    <div style={{ width: 190 }}>
                                        <InputItem
                                            {...getFieldProps('currentMonthSalary', {
                                                initialValue: talentInfo?.recruitTalentBackgroundSalary
                                                    ?.currentMonthSalary
                                                    ? `${talentInfo?.recruitTalentBackgroundSalary?.currentMonthSalary}`
                                                    : '',
                                                rules: [{ required: false, message: '请输入原月薪' }]
                                            })}
                                            // type="number"
                                            // maxLength={8}
                                            type="money"
                                            moneyKeyboardAlign="left"
                                            onChange={val => monthInputVal(val)}
                                            clear
                                            placeholder="请输入原月薪"
                                            moneyKeyboardWrapProps={moneyKeyboardWrapProps}
                                        />
                                    </div>
                                    <img alt="" src={xIcon} style={{ width: 20, height: 20, marginRight: 20 }} />
                                    <InputItem
                                        {...getFieldProps('monthCount', {
                                            initialValue: talentInfo?.recruitTalentBackgroundSalary?.monthCount
                                                ? `${talentInfo?.recruitTalentBackgroundSalary?.monthCount}`
                                                : '12',
                                            rules: [
                                                { required: true, message: '请输入月份' },
                                                {
                                                    validator(rule, value, callback) {
                                                        if (value && value < 12) {
                                                            callback('月份不可小于12');
                                                        }
                                                        callback();
                                                    }
                                                }
                                            ]
                                        })}
                                        type="number"
                                        maxLength={3}
                                        placeholder="请输入月份"
                                        style={{ width: 120 }}
                                    />
                                    <div>{form.getFieldValue('currentSalaryCurrencyCode')}</div>
                                </div>
                            </EditListItem>
                            <EditListItem title="原年薪" showArrow={false}>
                                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                                    <div style={{ width: 120, flexGrow: 1 }}>
                                        <InputItem
                                            {...getFieldProps('yearSalary', {
                                                initialValue: getCurrentYearSalary(
                                                    talentInfo?.recruitTalentBackgroundSalary?.currentMonthSalary,
                                                    talentInfo?.recruitTalentBackgroundSalary?.monthCount
                                                ),
                                                rules: [{ required: false, message: '请输入原年薪' }]
                                            })}
                                            // type="number"
                                            // maxLength={8}
                                            type="money"
                                            moneyKeyboardAlign="left"
                                            onChange={val => yearInputVal(val)}
                                            clear
                                            placeholder="请输入原年薪"
                                            moneyKeyboardWrapProps={moneyKeyboardWrapProps}
                                        />
                                    </div>
                                    <div>{form.getFieldValue('currentSalaryCurrencyCode')}</div>
                                </div>
                            </EditListItem>
                            <EditListItem title="薪资说明" showArrow={false} required={false}>
                                <TextareaItem
                                    className="customTextarea"
                                    autoHeight
                                    rows={4}
                                    count={1000}
                                    {...getFieldProps('currentSalaryDesc', {
                                        initialValue:
                                            talentInfo?.recruitTalentBackgroundSalary?.currentSalaryDesc ?? '',
                                        rules: [
                                            {
                                                max: 1000,
                                                message:
                                                    '示例：当前月薪资为税前薪资，不包含浮动的项目奖金，年终奖为2倍月薪。'
                                            }
                                        ]
                                    })}
                                    clear
                                    placeholder="示例：当前月薪资为税前薪资，不包含浮动的项目奖金，年终奖为2倍月薪。"
                                />
                            </EditListItem>
                            <EditListItem title="薪资证明" showArrow={false} required={false}>
                                <FileUploadMobile
                                    {...getFieldProps('salaryProveRelationsList', {
                                        rules: [
                                            {
                                                validator(rule, value = [], callback) {
                                                    const result = Array.isArray(value)
                                                        ? value
                                                        : value?.allFileList || value?.urlList || [];
                                                    let isAllFileUploaded = true;
                                                    if (hasIn(result[0], 'status')) {
                                                        isAllFileUploaded =
                                                            result.filter(f => f.status !== 'done').length === 0;
                                                    }
                                                    if (result.length && isAllFileUploaded) {
                                                        callback();
                                                    } else {
                                                        // callback('请上传薪资证明');
                                                        callback();
                                                    }
                                                }
                                            }
                                        ]
                                    })}
                                    categoryCode="talentSalaryProveFile"
                                    checkFileSize={10}
                                    checkFileSizeMsg="文件大小不能超过10MB！"
                                    checkFileType="JPG,JPEG,PNG,PDF"
                                    checkFileTypeMsg="只能上传JPG,JPEG,PNG,PDF格式的文件！"
                                    accept="image/*"
                                    showPreviewFile
                                >
                                    {size(form.getFieldValue('salaryProveRelationsList')?.allFileList) < 5 ? (
                                        <div
                                            style={{
                                                display: 'flex',
                                                justifyContent: 'center',
                                                alignItems: 'center',
                                                padding: '8px 0',
                                                color: '#FFA22D',
                                                fontSize: 16
                                            }}
                                        >
                                            <img alt="" src={add} width="20" height="20" style={{ marginRight: 4 }} />
                                            上传文件
                                        </div>
                                    ) : (
                                        <div></div>
                                    )}
                                </FileUploadMobile>
                                <div style={{ fontSize: 12, textAlign: 'center' }}>
                                    支持 zip、rar、doc、docx、jpg、jpeg、png、mp3 等格式的附件，单个文件大小为50M以内
                                </div>
                            </EditListItem>
                        </>
                    )}
                    <EditListItem title="期望年薪" showArrow={false}>
                        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                            <div style={{ width: 120, flexGrow: 1 }}>
                                <InputItem
                                    {...getFieldProps('expectSalary', {
                                        initialValue: talentInfo?.recruitTalentBackgroundSalary?.expectSalary
                                            ? `${talentInfo?.recruitTalentBackgroundSalary?.expectSalary}`
                                            : '',
                                        rules: [{ required: true, message: '请输入期望年薪' }]
                                    })}
                                    // type="number"
                                    // maxLength={8}
                                    type="money"
                                    moneyKeyboardAlign="left"
                                    onChange={val => expectYearInputVal(val)}
                                    clear
                                    placeholder="请输入期望年薪"
                                    moneyKeyboardWrapProps={moneyKeyboardWrapProps}
                                />
                            </div>
                            <div>
                                {' '}
                                {talentInfo?.recruitTalentBackgroundSalary?.expectSalaryCurrencyCode ||
                                    talentInfo?.recruitTalentBackgroundSalary?.companyCurrencyCode}
                            </div>
                        </div>
                    </EditListItem>
                    <EditListItem title="期望月薪" showArrow={false}>
                        <div style={{ display: 'flex', alignItems: 'center' }}>
                            <div style={{ width: 190 }}>
                                <InputItem
                                    {...getFieldProps('expectMonthSalary', {
                                        initialValue: getMonthSalary(
                                            talentInfo?.recruitTalentBackgroundSalary?.expectSalary,
                                            talentInfo?.recruitTalentBackgroundSalary?.expectMonthNumber
                                        ),
                                        rules: [{ required: true, message: '请输入期望月薪' }]
                                    })}
                                    // type="number"
                                    // maxLength={8}
                                    type="money"
                                    moneyKeyboardAlign="left"
                                    onChange={val => expectMonthInputVal(val)}
                                    clear
                                    placeholder="请输入期望月薪"
                                    moneyKeyboardWrapProps={moneyKeyboardWrapProps}
                                />
                            </div>
                            <img alt="" src={xIcon} style={{ width: 20, height: 20, marginRight: 20 }} />
                            <InputItem
                                {...getFieldProps('expectMonthNumber', {
                                    initialValue: talentInfo?.recruitTalentBackgroundSalary?.expectMonthNumber
                                        ? `${talentInfo?.recruitTalentBackgroundSalary?.expectMonthNumber}`
                                        : '12',
                                    rules: [
                                        { required: true, message: '请输入月份' },
                                        {
                                            validator(rule, value, callback) {
                                                if (value && value < 12) {
                                                    callback('月份不可小于12');
                                                }
                                                callback();
                                            }
                                        }
                                    ]
                                })}
                                type="number"
                                maxLength={3}
                                placeholder="请输入月份"
                                style={{ width: 120 }}
                            />
                            <div>
                                {' '}
                                {talentInfo?.recruitTalentBackgroundSalary?.expectSalaryCurrencyCode ||
                                    talentInfo?.recruitTalentBackgroundSalary?.companyCurrencyCode}
                            </div>
                        </div>
                    </EditListItem>
                </Spin>
            </div>
        </PageWrap>
    );
};

export default withRouter(createForm()(BackgroundIntensions));
